package admin

import (
	"fmt"
	"github.com/julienschmidt/httprouter"
	"net/http"
	"report/model"
	"report/reportdb"
	"strings"
)

func checkIsAdmin(request *http.Request) (bool, error) {
	auth := request.Header.Get("Authorization")
	fmt.Println(auth)
	token := strings.Split(auth, " ")[1]
	return reportdb.IsAdmin(token)
}

func AddUser(response http.ResponseWriter, request *http.Request, _ httprouter.Params) {
	isAdmin, adminErr := checkIsAdmin(request)
	if !isAdmin {
		response.Write([]byte(adminErr.Error()))
		response.WriteHeader(http.StatusUnauthorized)
		return
	}
	name := request.FormValue("name")
	pwd := request.FormValue("password")
	user := model.User{Name: name, Password: pwd, Role: "normal"}

	fmt.Printf("name:%s,pwd:%s", name, pwd)
	//	fmt.Println("name2:",params.ByName("name"))
	//	fmt.Println("name3:",request.FormValue("name"))
	err := reportdb.AddUser(user)
	if err != nil {
		panic(err)
		response.WriteHeader(http.StatusInternalServerError)
		response.Write([]byte(err.Error()))
		return
	}
	response.WriteHeader(http.StatusOK)
	response.Write([]byte("Success."))
}

func AddOrUpdateProduct(response http.ResponseWriter, request *http.Request, _ httprouter.Params) {
	isAdmin, adminErr := checkIsAdmin(request)
	if !isAdmin {
		response.Write([]byte(adminErr.Error()))
		response.WriteHeader(http.StatusUnauthorized)
		return
	}
	productName := request.FormValue("productName")
	version := request.Form["version"]

	product := model.Product{Name: productName, Version: version}
	err := reportdb.AddOrUpdateProduct(product)

	if err != nil {
		panic(err)
		response.WriteHeader(http.StatusInternalServerError)
		response.Write([]byte(err.Error()))
	}
	response.WriteHeader(http.StatusOK)
	response.Write([]byte("Success."))
}

func RemoveProduct(response http.ResponseWriter, request *http.Request, params httprouter.Params) {
	isAdmin, adminErr := checkIsAdmin(request)
	if !isAdmin {
		response.Write([]byte(adminErr.Error()))
		response.WriteHeader(http.StatusUnauthorized)
		return
	}
	productName := params.ByName("productname")
	err := reportdb.RemoveProduct(productName)
	if err != nil {
		panic(err)
		response.WriteHeader(http.StatusInternalServerError)
		response.Write([]byte(err.Error()))
	}
	response.WriteHeader(http.StatusOK)
	response.Write([]byte("Success."))
}

func GetProduct(response http.ResponseWriter, request *http.Request, params httprouter.Params) {
	isAdmin, adminErr := checkIsAdmin(request)
	if !isAdmin {
		response.WriteHeader(http.StatusUnauthorized)
		response.Write([]byte(adminErr.Error()))
		return
	}
	productName := params.ByName("productname")
	result, err := reportdb.GetProductByName(productName)
	if err != nil {
		panic(err)
		response.WriteHeader(http.StatusInternalServerError)
		response.Write([]byte(err.Error()))
	}
	response.WriteHeader(http.StatusOK)
	response.Write(result)
}
